﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace ExtractCSV
{
	public partial class ExtractCSV : Form
	{
		protected const string iGoogleNameSpace = @"http://www.google.com/ig";
		protected const string gadgetNameSpace = @"http://schemas.google.com/GadgetTabML/2008";
		protected XmlNamespaceManager _ns;

		private string _header = "Subject,Start Date";
		private List<string> _calendarEntries = new List<string>();

		public ExtractCSV()
		{
			InitializeComponent();
		}

		private void buttonOpenXml_Click(object sender, EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.DefaultExt = "xml";
			dlg.Filter = "xml files (*.xml)|*.xml";

			if(dlg.ShowDialog() == DialogResult.OK)
			{
				StreamReader r = new StreamReader(dlg.OpenFile());
				
				XmlDocument doc = new XmlDocument();
				doc.LoadXml(r.ReadToEnd());

				r.Close();

				_ns = new XmlNamespaceManager(doc.NameTable);
				_ns.AddNamespace(@"iGoogle", iGoogleNameSpace);
				_ns.AddNamespace(@"gadget", gadgetNameSpace);

				// Extract the data
				XmlNodeList months = doc.SelectNodes("//gadget:UserPref[contains(@name, 'dat')]", _ns);

				foreach (XmlNode month in months)
				{
					int monthOfYear = int.Parse(month.Attributes["name"].Value.Replace("dat", "")) + 1;

					string details = month.Attributes["value"].Value;
					details = details.Replace("&#39;", "'");
					string[] entries = details.Split(new string[]{"!,!"}, StringSplitOptions.RemoveEmptyEntries);

					foreach (string appointment in entries)
					{
						string[] bits = appointment.Split(new string[] { "!*!" }, StringSplitOptions.RemoveEmptyEntries);

						string[] dateBits = bits[0].Split('-');

						string date = monthOfYear.ToString() + "/" + dateBits[1] + "/" + dateBits[0];
						string eventDetails = bits[1];

						_calendarEntries.Add(eventDetails.Replace(",","") + "," + date);
					}
										
				}
			}

		}

		private void SaveCSV_Click(object sender, EventArgs e)
		{
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.DefaultExt = "csv";
			dlg.Filter = "csv files (*.csv)|*.csv";

			if (dlg.ShowDialog() == DialogResult.OK)
			{
				StreamWriter s = new StreamWriter(dlg.OpenFile());

				s.WriteLine(_header);
				foreach (string entry in _calendarEntries)
				{
					s.WriteLine(entry);
				}

				s.Close();
			}
		}
	}
}
